package com.my.aslife.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.my.aslife.mapper.TxMoneyMapper;
import com.my.aslife.module.common.ErrorCode;
import com.my.aslife.module.common.ResponseResult;
import com.my.aslife.module.common.UserIdThreadLocal;
import com.my.aslife.module.entity.TxMoney;
import com.my.aslife.module.entity.User;
import com.my.aslife.module.entity.dtos.DeductMoneyDto;
import com.my.aslife.module.entity.dtos.TxMoneyDto;
import com.my.aslife.service.IUserService;
import com.my.aslife.service.TxMoneyService;
import com.my.aslife.utils.SnowFlakeUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;

/**
 * @author mayuan
 * @description TODO
 */
@Service
@Slf4j
public class TxMoneyServiceImpl extends ServiceImpl<TxMoneyMapper, TxMoney> implements TxMoneyService {

    @Autowired
    private IUserService userService;


    @Override
    @Transactional
    public ResponseResult onWithdrawDeposit(TxMoneyDto txMoneyDto) {
        Integer uid = UserIdThreadLocal.get();
        User user = userService.queryUserById(uid);
        Integer money = user.getMoney();
        if (money < txMoneyDto.getMoney()) {
            return ResponseResult.failed(ErrorCode.MONEY_NOT_GOOD_ENOUGH);
        }

        Long id = SnowFlakeUtil.getId();
        TxMoney txMoney = new TxMoney();
        BeanUtils.copyProperties(txMoneyDto, txMoney);
        txMoney.setId(id);
        txMoney.setUid(Long.valueOf(uid));
        txMoney.setCreateTime(new Date());

        DeductMoneyDto deductMoneyDto = new DeductMoneyDto();
        deductMoneyDto.setMoney(txMoneyDto.getMoney());
        deductMoneyDto.setPhone(txMoneyDto.getPhone());
        deductMoneyDto.setUid(Long.valueOf(uid));
        deductMoneyDto.setTxMoney(txMoney);
        userService.deductMoney(deductMoneyDto);

        return ResponseResult.ok();
    }
}
